import {
	EditFormActionType,
	ICtrlActionResult,
	IEditFormAbility,
	IEditFormController,
	IEditFormControllerParams,
	IEditFormModel,
	IEditFormStore,
	IEvent,
	IHttpResponse,
	IParam,
} from '@/core/interface';
import {
	AuthUtil,
	DataTypeUtil,
	dateFormat,
	deepCopy,
	mergeViewParams,
	transformDoData,
	transformRawData,
} from '@/core/utils';
import { FormController } from './form-controller';

/**
 * 编辑表单控制器
 *
 * @export
 * @class EditFormController
 * @extends {FormController<EditFormActionType, IEditFormStore, IEditFormAbility>}
 * @implements {IEditFormController<IEditFormStore, IEditFormAbility>}
 */
export class EditFormController
	extends FormController<EditFormActionType, IEditFormStore, IEditFormAbility>
	implements IEditFormController<IEditFormStore, IEditFormAbility>
{
	/**
	 * 编辑表单模型
	 *
	 * @protected
	 * @type {IEditFormModel}
	 * @memberof EditFormController
	 */
	protected declare model: IEditFormModel;

	/**
	 * 保存回调
	 *
	 * @private
	 * @type {(Function | null)}
	 * @memberof EditFormController
	 */
	private saveCallback: Function | null = null;

	/**
	 * 关系界面数量
	 *
	 * @private
	 * @type {number}
	 * @memberof EditFormController
	 */
	private drNum: number = 0;

	/**
	 * 关系界面计数器
	 *
	 * @private
	 * @type {number}
	 * @memberof EditFormController
	 */
	private drCounter: number = 0;

	/**
	 * 多数据部件数量
	 *
	 * @private
	 * @type {number}
	 * @memberof EditFormController
	 */
	private mdNum: number = 0;

	/**
	 * 多数据部件计数器
	 *
	 * @private
	 * @type {number}
	 * @memberof EditFormController
	 */
	private mdCounter: number = 0;

	/**
	 * 主表单保存结果
	 *
	 * @private
	 * @type {Function}
	 * @memberof EditFormController
	 */
	private formSaveResolve!: Function;

	/**
	 * 行为模型
	 *
	 * @type {IParam}
	 * @memberof FormController
	 */
	private actionModel!: IParam;

	/**
	 * 是否可编辑
	 *
	 * @private
	 * @type {boolean}
	 * @memberof EditFormController
	 */
	private isEditable = false;

	/**
	 * 是否自动加载
	 *
	 * @private
	 * @type {boolean}
	 * @memberof EditFormController
	 */
	private autoLoad = false;

	/**
	 * Creates an instance of EditFormController.
	 * @param {IEditFormControllerParams<EditFormActionType, IEditFormAbility>} params
	 * @memberof EditFormController
	 */
	public constructor(
		params: IEditFormControllerParams<EditFormActionType, IEditFormAbility>
	) {
		super(params);
		this.ctrlInit(params);
	}

	/**
	 * 处理部件初始化
	 *
	 * @protected
	 * @param {IEditFormControllerParams<EditFormActionType, IEditFormAbility>} params
	 * @memberof EditFormController
	 */
	protected processCtrlInit(
		params: IEditFormControllerParams<EditFormActionType, IEditFormAbility>
	) {
		super.processCtrlInit(params);
		this.isEditable = params.isEditable;
		this.autoLoad = !!params.autoLoad;
		Object.assign(this.store, {
			anchorData: [],
		});
		this.initActionModel();
		this.computeDrCount();
		this.setAnchorData();
	}

	/**
	 * 部件挂载
	 *
	 * @memberof EditFormController
	 */
	public ctrlMounted(): void {
		super.ctrlMounted();
		if (this.autoLoad) {
			this.load();
		}
	}

	/**
	 * 初始化行为模型
	 *
	 * @private
	 * @memberof EditFormController
	 */
	private initActionModel() {
		const { detailModel } = this.model;
		this.actionModel = {};
		Object.values(detailModel).forEach((detail: IParam) => {
			if (detail.detailType === 'BUTTON') {
				if (detail.uIAction) {
					Object.assign(this.actionModel, {
						[detail.uIAction.uIActionTag]: {
							disabled: detail.uIAction.disabled,
							visible: detail.uIAction.visible,
							noPrivDisplayMode: detail.uIAction.noPrivDisplayMode,
							dataAccessAction: detail.uIAction.dataAccessAction,
							actionTarget: detail.uIAction.actionTarget,
						},
					});
				}
			} else if (detail.detailType === 'GROUPPANEL') {
				if (detail.uIActionGroup?.details.length > 0) {
					detail.uIActionGroup.details.forEach((item: IParam) => {
						Object.assign(this.actionModel, {
							[item.uIActionTag]: {
								disabled: item.disabled,
								visible: item.visible,
								noPrivDisplayMode: item.noPrivDisplayMode,
								dataAccessAction: item.dataAccessAction,
								actionTarget: item.actionTarget,
							},
						});
					});
				}
			}
		});
	}

	/**
	 * 计算关系界面数量
	 *
	 * @private
	 * @memberof EditFormController
	 */
	private computeDrCount() {
		this.drNum = 0;
		this.mdNum = 0;
		Object.values(this.model.detailModel).forEach((item: any) => {
			if (item.detailType === 'DRUIPART') {
				this.drNum += 1;
			}
			if (item.detailType === 'MDCTRL' && !item.parentIsRepeater) {
				this.mdNum += 1;
			}
		});
	}

	/**
	 * 设置锚点数据
	 *
	 * @private
	 * @memberof EditFormController
	 */
	private setAnchorData() {
		this.store.anchorData = [];
		Object.values(this.model.detailModel).forEach((item: any) => {
			if (item.enableAnchor) {
				this.store.anchorData.push({
					caption: item.caption,
					codeName: item.codeName,
				});
			}
		});
	}

	/**
	 * 加载数据
	 *
	 * @param {IParam} [opts={}] 行为参数
	 * @return {*}  {Promise<ICtrlActionResult>}
	 * @memberof EditFormController
	 */
	public async load(opts: IParam = {}): Promise<ICtrlActionResult> {
		const { loadAction } = this.actions;
		const { viewParams, context } = this.store;
		const { name, entityCodeName } = this.model;
		if (!loadAction) {
			App.getNotificationHelper().error(
				App.ts('app.notificationtitle.error'),
				App.ts('widget.editform.notconfig.loadaction')
			);
			return { ok: false, data: this.getData(), rowData: { status: 500 } };
		}
		const arg: IParam = { ...opts };
		Object.assign(arg, viewParams);
		const tempContext = deepCopy(context);
		if (opts[entityCodeName.toLowerCase()]) {
			Object.assign(tempContext, {
				[entityCodeName.toLowerCase()]: opts[entityCodeName.toLowerCase()],
			});
			delete opts[entityCodeName.toLowerCase()];
		}
		const res = await this.beforeAsyncAction('load', tempContext, arg);
		if (!res.ok) {
			return { ok: false, data: this.getData(), rowData: { status: 500 } };
		}
		try {
			const response: IHttpResponse = await this.ctrlService.get(
				loadAction,
				tempContext,
				{ viewParams: arg }
			);
			const res = await this.afterAsyncAction('load', response);
			if (!res.ok) {
				return { ok: false, data: this.getData(), rowData: { status: 500 } };
			}
			if (response.success) {
				if (this.store.viewParams.copymode) {
					response.data.srfmajortext += '- 副本';
				}
				await this.afterFormAction('load', response.data);
				this.emit('load', this.getData());
				this.executeFromDetailAbility({
					name: name,
					action: 'load',
					data: this.store.data,
				});

				return { ok: true, data: this.getData(), rowData: response };
			}
			return { ok: false, data: this.getData(), rowData: response };
		} catch (error: any) {
			await this.afterAsyncAction('load', error);
			return { ok: false, data: this.getData(), rowData: error };
		}
	}

	/**
	 * 加载草稿
	 *
	 * @param {IParam} [opts={}] 行为参数
	 * @return {*}  {Promise<ICtrlActionResult>}
	 * @memberof EditFormController
	 */
	public async loadDraft(opts: IParam = {}): Promise<ICtrlActionResult> {
		const { loadDraftAction } = this.actions;
		const { viewParams, context } = this.store;
		if (!loadDraftAction) {
			App.getNotificationHelper().error(
				App.ts('app.notificationtitle.error'),
				App.ts('widget.editform.notconfig.loaddraftaction')
			);
			return { ok: false, data: this.getData(), rowData: { status: 500 } };
		}
		const arg: any = { ...opts };
		Object.assign(arg, viewParams);
		const tempContext = deepCopy(context);
		const res = await this.beforeAsyncAction('loadDraft', tempContext, arg);
		if (!res.ok) {
			return { ok: false, data: this.getData(), rowData: { status: 500 } };
		}
		try {
			const response: IHttpResponse = await this.ctrlService.loadDraft(
				loadDraftAction,
				tempContext,
				{ viewParams: arg }
			);
			const res = await this.afterAsyncAction('loadDraft', response);
			if (!res.ok) {
				return { ok: false, data: this.getData(), rowData: { status: 500 } };
			}
			if (response.success) {
				await this.afterFormAction('loadDraft', response.data);
				this.emit('loadDraft', this.getData());
				this.executeFromDetailAbility({
					name: this.name,
					action: 'load',
					data: this.store.data,
				});
				return { ok: true, data: this.getData(), rowData: response };
			}
			return { ok: false, data: this.getData(), rowData: response };
		} catch (error: any) {
			this.afterAsyncAction('load', error);
			return { ok: false, data: this.getData(), rowData: error };
		}
	}

	/**
	 * 删除数据
	 *
	 * @param {IParam} [opts={}] 行为参数
	 * @return {*}  {Promise<ICtrlActionResult>}
	 * @memberof EditFormController
	 */
	public async remove(opts: IParam = {}): Promise<ICtrlActionResult> {
		const { removeAction } = this.actions;
		const { viewParams, context, data } = this.store;
		if (!removeAction) {
			App.getNotificationHelper().error(
				App.ts('app.notificationtitle.error'),
				App.ts('widget.editform.notconfig.removeaction')
			);
			return { ok: false, data: this.getData(), rowData: { status: 500 } };
		}
		const arg: any = { ...opts };
		Object.assign(arg, viewParams);
		const tempContext = deepCopy(context);
		const res = await this.beforeAsyncAction('remove', tempContext, arg);
		if (!res.ok) {
			return { ok: false, data: this.getData(), rowData: { status: 500 } };
		}
		try {
			const response: IHttpResponse = await this.ctrlService.delete(
				removeAction,
				tempContext,
				{
					data,
					viewParams: arg,
				}
			);
			const res = await this.afterAsyncAction('remove', response);
			if (!res.ok) {
				return { ok: false, data: this.getData(), rowData: { status: 500 } };
			}
			if (response.success) {
				this.emit('remove', this.getData());
				this.executeFromDetailAbility({
					name: this.name,
					action: 'remove',
					data: data,
				});
				App.getNotificationHelper().success(
					App.ts('app.notificationtitle.success'),
					`${data.srfmajortext} ${App.ts('widget.editform.removesuccess')}！`
				);
				return { ok: true, data: this.getData(), rowData: response };
			}
			return { ok: false, data: this.getData(), rowData: response };
		} catch (error: any) {
			await this.afterAsyncAction('remove', error);
			return { ok: false, data: this.getData(), rowData: error };
		}
	}

	/**
	 * 保存数据
	 *
	 * @param {IParam} [opts={}] 行为参数
	 * @param {boolean} [showResultInfo=true] 是否显示结果信息
	 * @param {boolean} [isStateNext=true] 是否执行保存关系界面
	 * @return {*}  {Promise<ICtrlActionResult>}
	 * @memberof EditFormController
	 */
	public save(
		opts: IParam = {},
		showResultInfo = true,
		isStateNext = true
	): Promise<ICtrlActionResult> {
		return new Promise(async (resolve: Function, reject: Function) => {
			if (this.validate && !(await this.validate())) {
				App.getNotificationHelper().error(
					App.ts('app.notificationtitle.error'),
					`${
						this.store.data.srfmajortext ? this.store.data.srfmajortext : ''
					} ${App.ts('widget.editform.formvalidate')}！`
				);
				return reject({ ok: false, data: this.getData(), rowData: null });
			}
			const { updateAction, createAction } = this.actions;
			const { viewParams, context, data } = this.store;
			if (viewParams.copymode) {
				data.srfuf = '0';
			}
			const action: string | undefined = Object.is(data.srfuf, '1')
				? updateAction
				: createAction;
			if (!action) {
				App.getNotificationHelper().error(
					App.ts('app.notificationtitle.error'),
					`${
						Object.is(data.srfuf, '1')
							? App.ts('widget.editform.notconfig.updateaction')
							: App.ts('widget.editform.notconfig.createaction')
					}！`
				);
				return reject({ ok: false, data: this.getData(), rowData: null });
			}
			const arg: IParam = { ...opts };
			Object.assign(arg, deepCopy(viewParams));
			const tempContext = deepCopy(context);
			const res = await this.beforeAsyncAction('save', tempContext, arg);
			if (!res.ok) {
				return { ok: false, data: this.getData(), rowData: { status: 500 } };
			}
			if (isStateNext && (this.drNum > 0 || this.mdNum > 0)) {
				this.drCounter = this.drNum;
				this.mdCounter = this.mdNum;
				this.formSaveResolve = resolve;
				this.saveCallback = () => {
					return this.save(opts, true, false);
				};
				this.executeFromDetailAbility({
					name: this.name,
					action: 'beforeSave',
					data: data,
				});
				return;
			}
			try {
				const response: IHttpResponse = await this.ctrlService[
					Object.is(data.srfuf, '1') ? 'update' : 'create'
				](action, tempContext, Object.assign(data, { viewParams: arg }));
				const res = await this.afterAsyncAction('save', response);
				if (!res.ok) {
					return { ok: false, data: this.getData(), rowData: { status: 500 } };
				}
				if (response.success) {
					if (this.store.viewParams.hasOwnProperty('copymode')) {
						delete this.store.viewParams.copymode;
					}
					await this.afterFormAction('save', response.data);
					this.emit('save', this.getData());
					this.executeFromDetailAbility({
						name: this.name,
						action: 'save',
						data: this.store.data,
					});
					if (showResultInfo) {
						App.getNotificationHelper().success(
							App.ts('app.notificationtitle.success'),
							`${this.store.data.srfmajortext || ''} ${App.ts(
								'widget.editform.savesuccess'
							)}！`
						);
					}
					return resolve({ ok: true, data: this.getData(), rowData: response });
				} else {
					//保存失败抛出空数据
					this.emit('save', []);
				}
				return reject({ ok: false, data: this.getData(), rowData: response });
			} catch (error: any) {
				await this.afterAsyncAction('save', error);
				return reject({ ok: false, data: this.getData(), rowData: error });
			}
		});
	}

	/**
	 * 工作流启动
	 *
	 * @param {IParam[]} data
	 * @param {IParam} [localData]
	 * @return {*}  {Promise<ICtrlActionResult>}
	 * @memberof EditFormController
	 */
	public wfStart(
		data: IParam[],
		localData?: IParam
	): Promise<ICtrlActionResult> {
		return new Promise(async (resolve: Function, reject: Function) => {
			//	主信息文本
			const majorText = this.store.data.srfmajortext
				? this.store.data.srfmajortext
				: '';
			if (this.validate && !(await this.validate())) {
				App.getNotificationHelper().error(
					App.ts('app.notificationtitle.error'),
					`${majorText} ${App.ts('widget.editform.formvalidate')}！`
				);
				return reject({ ok: false, data: this.getData(), rowData: null });
			}
			const formData = this.store.data;
			const copyData = deepCopy(data && data.length > 0 ? data[0] : {});
			Object.assign(formData, { viewParams: copyData });
			const tempContext = deepCopy(this.store.context);
			const res = await this.beforeAsyncAction('save', tempContext, formData);
			if (!res.ok) {
				return { ok: false, data: this.getData(), rowData: { status: 500 } };
			}
			try {
				const response =
					formData.srfuf === '1'
						? await this.ctrlService.update('Update', tempContext, formData)
						: await this.ctrlService.create('Create', tempContext, formData);
				await this.afterAsyncAction('save', response);
				if (response.success) {
					//	表单保存完成数据
					const responseData: IParam = transformRawData(response.data);
					const arg = deepCopy(responseData);
					await this.afterFormAction('save', response.data);
					this.emit('save', this.getData());

					//	准备工作流数据，填充未存库数据
					if (copyData && Object.keys(copyData).length > 0) {
						Object.keys(copyData).forEach((key: string) => {
							if (
								!data.hasOwnProperty(key) ||
								(data.hasOwnProperty(key) && copyData[key])
							) {
								responseData[key] = copyData[key];
							}
						});
					}

					//	合并视图参数
					const tempViewParams = deepCopy(this.store.viewParams);
					if (tempViewParams.w) {
						delete tempViewParams.w;
					}
					const { keyPSAppDEField, majorPSAppDEField } = this.model;
					if (
						keyPSAppDEField &&
						tempViewParams[keyPSAppDEField.toLowerCase()]
					) {
						delete tempViewParams[keyPSAppDEField.toLowerCase()];
					}
					if (
						majorPSAppDEField &&
						tempViewParams[majorPSAppDEField.toLowerCase()]
					) {
						delete tempViewParams[majorPSAppDEField.toLowerCase()];
					}
					//	合并视图参数
					mergeViewParams(responseData, tempViewParams);

					Object.assign(arg, { viewParams: transformDoData(responseData) });

					const { wfStartAction } = this.actions;
					if (!wfStartAction) {
						reject({ ok: false, data: this.getData(), rowData: null });
						return;
					}
					const res = await this.beforeAsyncAction(
						'wfstart',
						tempContext,
						responseData
					);
					if (!res.ok) {
						return {
							ok: false,
							data: this.getData(),
							rowData: { status: 500 },
						};
					}
					const startResponse = await this.ctrlService.wfStart(
						wfStartAction,
						tempContext,
						arg,
						localData
					);
					const afterRes = await this.afterAsyncAction(
						'wfstart',
						startResponse
					);
					if (!afterRes.ok) {
						return {
							ok: false,
							data: this.getData(),
							rowData: { status: 500 },
						};
					}
					if (startResponse.success) {
						App.getNotificationHelper().success(
							App.ts('app.notificationtitle.success'),
							`${majorText} ${App.ts(
								'widget.editform.workflow.startsuccess'
							)}！`
						);
						resolve({ ok: true, data: this.getData(), rowData: startResponse });
					} else {
						resolve({
							ok: false,
							data: this.getData(),
							rowData: startResponse,
						});
					}
				}
			} catch (error: any) {
				await this.afterAsyncAction('wfstart', error);
				return reject({ ok: false, data: this.getData(), rowData: null });
			}
		});
	}

	/**
	 * 工作流提交
	 *
	 * @param {IParam[]} data
	 * @param {IParam} [opts={}]
	 * @return {*}  {Promise<ICtrlActionResult>}
	 * @memberof EditFormController
	 */
	public wfSubmit(
		data: IParam[],
		opts: IParam = {}
	): Promise<ICtrlActionResult> {
		return new Promise(async (resolve: Function, reject: Function) => {
			//	主信息文本
			const majorText = this.store.data.srfmajortext
				? this.store.data.srfmajortext
				: '';
			if (this.validate && !(await this.validate())) {
				App.getNotificationHelper().error(
					App.ts('app.notificationtitle.error'),
					`${majorText} ${App.ts('widget.editform.formvalidate')}！`
				);
				return reject({ ok: false, data: this.getData(), rowData: null });
			}
			const { viewParams, context } = this.store;
			const arg: any = { ...data[0] };
			delete arg.$DO;
			const copyData = deepCopy(arg);
			const tempViewParams = deepCopy(viewParams);
			const tempContext = deepCopy(context);
			Object.assign(arg, { viewParams: tempViewParams });
			const submitData = async (responseData: IParam) => {
				const arg = deepCopy(responseData);
				Object.assign(arg, copyData);
				if (this.store.viewParams) {
					Object.assign(responseData, this.store.viewParams);
				}
				Object.assign(arg, { viewParams: responseData });
				const { wfSubmitAction } = this.actions;
				const res = await this.beforeAsyncAction('wfSubmit', tempContext, arg);
				if (!res.ok) {
					return { ok: false, data: this.getData(), rowData: { status: 500 } };
				}
				try {
					const response: IHttpResponse = await this.ctrlService.wfSubmit(
						wfSubmitAction ? wfSubmitAction : 'WFSubmit',
						tempContext,
						arg,
						opts
					);
					const res = await this.afterAsyncAction('wfSubmit', response);
					if (!res.ok) {
						return {
							ok: false,
							data: this.getData(),
							rowData: { status: 500 },
						};
					}
					if (response.success) {
						await this.afterFormAction('submit', response.data);
						App.getNotificationHelper().success(
							App.ts('app.notificationtitle.success'),
							`${majorText} ${App.ts(
								'widget.editform.workflow.submitsuccess'
							)}！`
						);
						return resolve({
							ok: true,
							data: this.getData(),
							rowData: response,
						});
					}
					App.getNotificationHelper().error(
						App.ts('app.notificationtitle.error'),
						`${majorText} ${App.ts('widget.editform.workflow.submitfailure')}！`
					);
					return reject({ ok: false, data: this.getData(), rowData: response });
				} catch (error) {
					App.getNotificationHelper().error(
						App.ts('app.notificationtitle.error'),
						`${majorText} ${App.ts('widget.editform.workflow.submitfailure')}！`
					);
					return reject({ ok: false, data: this.getData(), rowData: error });
				}
			};
			const action: any = Object.is(data[0].srfuf, '1') ? 'Update' : 'Create';
			const res = await this.beforeAsyncAction('save', tempContext, arg);
			if (!res.ok) {
				return { ok: false, data: this.getData(), rowData: { status: 500 } };
			}
			try {
				const response: IHttpResponse = await this.ctrlService[
					Object.is(data[0].srfuf, '1') ? 'update' : 'create'
				](action, tempContext, arg);
				const res = await this.afterAsyncAction('save', response);
				if (!res.ok) {
					return { ok: false, data: this.getData(), rowData: { status: 500 } };
				}
				if (response.success) {
					await this.afterFormAction('save', response.data);
					this.emit('save', this.getData());
					return submitData(transformDoData(response.data));
				}
				reject({ ok: false, data: this.getData(), rowData: response });
			} catch (error: any) {
				await this.afterAsyncAction('wfSubmit', error);
				reject({ ok: false, data: this.getData(), rowData: error });
			}
		});
	}

	/**
	 * 处理表单值改变
	 *
	 * @param {string} name 表单项名称
	 * @param {*} value 表单项值
	 * @return {*}  {Promise<void>}
	 * @memberof EditFormController
	 */
	protected async handleFormValueChange(
		name: string,
		value: any
	): Promise<void> {
		super.handleFormValueChange(name, value);
		const { enableAutoSave } = this.model;
		if (
			!name ||
			!this.store.data.hasOwnProperty(name) ||
			this.checkIgnoreInput(name, 'before')
		) {
			return;
		}
		this.store.data[name] = value;
		await this.resetFormItem(name);
		this.formDynamicLogic(name);
		await this.formItemUpdate(name);
		this.executeFromDetailAbility({
			name: name,
			action: 'valueChange',
			data: this.store.data,
		});
		if (enableAutoSave) {
			await this.save();
		}
		this.emit('dataChange', this.getData());
	}

	/**
	 * 处理表单关系界面保存
	 *
	 * @private
	 * @return {*}  {Promise<void>}
	 * @memberof EditFormController
	 */
	private async handleDetailDataSaved(data: IParam): Promise<void> {
		if (data.type == 'DRUIPART') {
			this.drCounter--;
		} else if (data.type == 'MDCTRL') {
			this.mdCounter--;
		}
		if (this.drCounter == 0 && this.mdCounter == 0 && this.saveCallback) {
			const response = await this.saveCallback();
			this.formSaveResolve(response);
		}
	}

	/**
	 * 处理组件行为
	 *
	 * @param {IEvent<string>} actionParam 行为参数
	 * @memberof EditFormController
	 */
	public handleComponentAction(actionParam: IEvent<string>): void {
		super.handleComponentAction(actionParam);
		const { name, action, data } = actionParam;
		switch (action) {
			case 'viewDataSave':
				this.handleDetailDataSaved(data);
				break;
			case 'mdCtrlDataSave':
				this.handleDetailDataSaved(data);
				break;
			case 'mdCtrlUpdateDefault':
				this.setUpdateDefault(name, data);
				break;
			case 'mdCtrlCreateDefault':
				this.setCreateDefault(name, data);
				break;
		}
	}

	/**
	 * 表单执行数据行为之后
	 * 1.根据行为类型将主键合并到context中
	 * 2.将行为数据合并到表单数据中
	 * 3.设置更新默认值
	 * 4.计算行为权限状态
	 * 5.设置表单项启用
	 * 6.表单动态逻辑
	 * 7.表单项更新
	 * 8.转化代码项文本
	 * @protected
	 * @param {string} action
	 * @param {IParam} data
	 * @memberof EditFormController
	 */
	protected async afterFormAction(action: string, data: IParam) {
		const { entityCodeName, keyPSAppDEField, detailModel } = this.model;
		if (Object.is(action, 'save') || Object.is(action, 'submit')) {
			if (entityCodeName && this.store.data[entityCodeName.toLowerCase()]) {
				Object.assign(this.store.context, {
					[entityCodeName.toLowerCase()]:
						this.store.data[entityCodeName.toLowerCase()],
				});
			}
		}
		this.store.data = data;
		if (Object.is(action, 'load')) {
			this.setUpdateDefault();
			this.setFormEnableCond();
		}
		if (Object.is(action, 'loadDraft')) {
			// 表单加载草稿后设置srfuf为'0'，将数据标记为新建
			this.store.data.srfuf = '0';
			this.setCreateDefault();
			this.setFormEnableCond();
		}
		// 如果表单项有主键，表示主键可编辑
		if (detailModel.hasOwnProperty(keyPSAppDEField.toLowerCase())) {
			this.store.data.srffrontuf = 1;
		}
		await this.calcActionAuthState();
		this.formDynamicLogic('');
		await this.formItemUpdate('');
		// await this.translateCodeListText();
	}

	/**
	 * 计算行为权限状态
	 *
	 * @private
	 * @memberof EditFormController
	 */
	private async calcActionAuthState() {
		const { entityCodeName } = this.model;
		const { context } = this.store;
		const tempModel = deepCopy(this.actionModel);
		const UIService = await App.getUIService(entityCodeName, context);
		AuthUtil.calcActionItemAuthState(
			this.store.data,
			tempModel,
			UIService,
			this.store.viewCtx.view?.getModel()
		);
		Object.values(this.store.detailModel).forEach((item: IParam) => {
			if (Object.is(item.detailType, 'BUTTON') && item.uIAction?.uIActionTag) {
				// 更新按钮的权限状态值
				item.visible = tempModel[item.uIAction.uIActionTag].visible;
				item.disabled = tempModel[item.uIAction.uIActionTag].disabled;
			} else if (
				Object.is(item.detailType, 'GROUPPANEL') &&
				item.uIActionGroup?.details?.length > 0
			) {
				// 更新分组面板界面行为组的权限状态值
				item.uIActionGroup.details.forEach((actionDetail: any) => {
					actionDetail.visible = tempModel[actionDetail.uIActionTag].visible;
					actionDetail.disabled = tempModel[actionDetail.uIActionTag].disabled;
				});
			}
		});
	}

	/**
	 * 设置更新默认值
	 *
	 * @private
	 * @param {string} [name]
	 * @param {IParam[]} [data]
	 * @memberof EditFormController
	 */
	private setUpdateDefault(name?: string, data?: IParam[]) {
		const updateDefaultItems = name
			? this.store.detailModel[name]?.updateDefaultItems
			: this.model.updateDefaultItems;
		const { viewParams, context } = this.store;
		const setValue = (updateDefault: IParam, item: IParam) => {
			const { updateDV, updateDVT, property, dataType, valueFormat } =
				updateDefault;
			if ((updateDV || updateDVT) && !item[property]) {
				switch (updateDVT) {
					case 'CONTEXT':
						item[property] = viewParams[updateDV];
						break;
					case 'SESSION':
						item[property] = context[updateDV];
						break;
					case 'APPDATA':
						item[property] = context[updateDV];
						break;
					case 'OPERATORNAME':
						item[property] = context['srfusername'];
						break;
					case 'OPERATOR':
						item[property] = context['srfuserid'];
						break;
					case 'CURTIME':
						item[property] = dateFormat(new Date(), valueFormat);
						break;
					case 'PARAM':
						item[property] =
							this.ctrlService.getRemoteCopyData()[property] || null;
						break;
					default:
						item[property] = DataTypeUtil.isNumber(dataType)
							? Number(updateDV)
							: updateDV;
						break;
				}
			}
		};
		updateDefaultItems?.forEach((updateDefault: IParam) => {
			if (name) {
				data?.forEach((item: IParam) => {
					setValue(updateDefault, item);
				});
			} else {
				setValue(updateDefault, this.store.data);
			}
		});
	}

	/**
	 * 面板行为
	 *
	 * @param {string} [action] 调用的实体行为
	 * @param {string} [emitAction] 抛出行为
	 * @param {*} [data={}] 传入数据
	 *
	 * @memberof EditFormController
	 */
	public async panelAction(
		action: string,
		emitAction: EditFormActionType,
		data: any = {}
	): Promise<void> {
		if (!action || (action && Object.is(action, ''))) {
			return;
		}
		const arg: any = { ...data };
		const formdata = this.getData()[0];
		const { viewParams, context } = this.store;
		const tempViewParams = deepCopy(viewParams);
		const tempContext = deepCopy(context);
		Object.assign(arg, formdata);
		mergeViewParams(arg, tempViewParams);
		const { entityCodeName } = this.model;
		if (data[entityCodeName.toLowerCase()]) {
			Object.assign(tempContext, {
				[entityCodeName.toLowerCase()]: data[entityCodeName.toLowerCase()],
			});
		}
		this.beforeAsyncAction('panelAction', tempContext, arg);
		const post: Promise<any> = this.ctrlService.frontLogic(
			action,
			tempContext,
			arg
		);
		post
			.then(async (response: any) => {
				this.afterAsyncAction('panelAction', response);
				if (response.success) {
					const data = response.data;
					await this.afterFormAction(emitAction, data);
					this.emit(emitAction, this.getData());
				}
			})
			.catch((response: any) => {
				this.afterAsyncAction('panelAction', response);
			});
	}

	/**
	 * 获取成员模型
	 *
	 * @return {*}  {IParam}
	 * @memberof EditFormController
	 */
	getDetailModel(): IParam {
		return this.store.detailModel;
	}

	/**
	 * 刷新
	 *
	 * @param {(IParam | undefined)} [args]
	 * @return {*}  {Promise<boolean>}
	 * @memberof EditFormController
	 */
	public async refresh(args?: IParam | undefined): Promise<boolean> {
		try {
			const result = await this.load(args || {});
			if (result.ok) {
				return true;
			}
		} catch (error) {
			return false;
		}
		return false;
	}

	/**
	 * 获取能力
	 *
	 * @return {*}  {IEditFormAbility}
	 * @memberof EditFormController
	 */
	getAbility(): IEditFormAbility {
		return {
			...super.getAbility(),
			load: this.load.bind(this),
			save: this.save.bind(this),
			remove: this.remove.bind(this),
			wfStart: this.wfStart.bind(this),
			wfSubmit: this.wfSubmit.bind(this),
			getDetailModel: this.getDetailModel.bind(this),
			panelAction: this.panelAction.bind(this),
		};
	}
}
